package com.nexttwist.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

import com.nexttwist.model.Comment;

public class CommentsDAO extends BaseDAO {

		private String[] allColumns = { "commentId", "trackId", "comment", "userId" };

		public Comment createComment(Context context, Comment comment) {
			try{
				BaseDAO.openDatabaseRead(context);
				ContentValues values = new ContentValues();
				
				values.put("trackId", comment.getTrackId());
				values.put("comment", comment.getComment());
				values.put("userId", comment.getUserId());
	
				database.insert(SqlLiteHelper.TABLE_COMMENT, null, values);
				
			} catch (Exception e) {
				System.out.println(e.getMessage());
			} finally {
				BaseDAO.closeDatabaseRead();
			}
			return comment;
		}

		public void deleteTrack(Context context, Comment comment) {
			try{
				BaseDAO.openDatabaseRead(context);
				long id = comment.getCommentId();
				System.out.println("Comment deleted with id: " + id);
				database.delete(SqlLiteHelper.TABLE_COMMENT, "commentId = " + id, null);
			} catch (Exception e) {
				System.out.println(e.getMessage());
			} finally {
				BaseDAO.closeDatabaseRead();
			}
		}

		public List<Comment> getAllComments(Context context) {
			List<Comment> comments = new ArrayList<Comment>();
			try{
				BaseDAO.openDatabaseRead(context);
	
				Cursor cursor = database.query(SqlLiteHelper.TABLE_COMMENT, allColumns, null, null, null, null, null);
				cursor.moveToFirst();
				
				while (!cursor.isAfterLast()) {
					Comment comment = cursorToComment(cursor);
					comments.add(comment);
					cursor.moveToNext();
				}
				// make sure to close the cursor
				cursor.close();
			} catch (Exception e) {
				System.out.println(e.getMessage());
			} finally {
				BaseDAO.closeDatabaseRead();
			}
			return comments;
		}

		private Comment cursorToComment(Cursor cursor) {
			Comment comment = new Comment();
			comment.setCommentId(cursor.getInt(0));
			comment.setTrackId(cursor.getInt(1));
			comment.setComment(cursor.getString(2));
			comment.setUserId(cursor.getInt(3));
			return comment;
		}
}
